<template>
	<view>
		<cu-custom :bgColor="'bg-' + theme.backgroundColor" :isBack="false">
			<block slot="backText">返回</block>
			<block slot="content">首页</block>
		</cu-custom>
		<view class="uni-margin-wrap bg-white" v-if="swiperList.length">
			<swiper circular autoplay :interval="5000" :duration="500">
				<swiper-item v-for="(item, index) in swiperList" :key="index">
					<view class="swiper-item">
						<image :src="item.image" mode="widthFix" />
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="user flex">
			<view class="avtar">
				<image :src="user.headimgUrl" mode="scaleToFill" />
			</view>
			<view class="">{{ user.nickName || '微信用户' }}</view>
		</view>
		<scroll-view scroll-x class="bg-white nav collection-types">
			<view class="flex text-center">
				<view :class="'cu-item flex-sub ' + (item.value == tabCur ? 'cur text-' + theme.themeColor : '')"
					v-for="(item, index) in tab" :key="index" @tap="tabSelect(item)">{{ item.title }}</view>
			</view>
		</scroll-view>
		<view class="example" v-if="innerflag&&tabCur=='2'&&liveList.length==0" style="width: 100%;">
			<video id="myVideo"
				src="https://huachuang-zhibo.oss-cn-beijing.aliyuncs.com/%E5%85%BB%E7%94%9F%E5%85%AD%E5%AD%97%E8%AF%80.mp4"
				:controls="false" loop style="margin: 30rpx auto;display: block;" :autoplay="false"></video>
		</view>
		<view class="live-list">
			<view class="live-item bg-white" v-for="(item, index) in liveList" :key="index">
				<view class="flex">
					<view class="coverImage">
						<image :src="item.coverImage" mode="scaleToFill" />
					</view>
					<view class="content pt20 pb20 pr20 flex1">
						<view class="f22">开始时间:{{ item.startTime }}</view>
						<view class="f26 text-line2 mt10">名称:{{ item.liveName }} </view>
						<view class="btn-box text-right mt20 w100">
							<button class="cu-btn border-radius mr10" :class="'bg-' + theme.themeColor"
								v-if="user.tzFlag == 1" open-type="share" @tap.stop="liveShare(item)">分享</button>
							<button class="cu-btn border-radius" :class="'bg-' + theme.themeColor" @tap="goLive(item)">
								{{tabCur == '1'
										? user.tzFlag == 1
										? item.isReward == 0
										? '设置'
										: '修改设置'
										: '订阅提醒'
										: tabCur == '2'
										? '进入'
										: tabCur == '3'
										? '观看回放'
										: ''
								}}
							</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view :class="'cu-load bg-gray ' + (loadmore ? 'loading' : 'over')"></view>
	</view>
</template>
<script>
	const app = getApp();
	import util from 'utils/util';
	import api from 'utils/api';
	export default {
		data() {
			return {
				innerflag: false,
				theme: app.globalData.theme, //全局颜色变量
				swiperList: [],
				user: {},
				tab: [{
					title: '未开始',
					value: '1'
				}, {
					title: '进行中',
					value: '2'
				}, {
					title: '已结束',
					value: '3'
				}],
				tabCur: '1',
				liveList: [],
				page: {
					current: 1,
					size: 500
				},
				total: 0,
				loadmore: false,
				liveId: '',
				shareType: '',
				tzUserId: '',
				liveShareInfo: {},
				videoContext: {},
				liveListLength: 0
			};
		},
			onShareAppMessage(res) {
				if (this.liveShareInfo.forward == 1) {
					return {
						title: this.liveShareInfo.liveShareInfo, //自定义标题
						path: '/pages/home/index?liveId=' + this.liveShareInfo.id + '&code=' + this.user.id + '&type=1' +
							`&tabCur=${this.tabCur}`,
						imageUrl: this.liveShareInfo.stopImage //自定义展示图片
					};
				} else {
					wx.updateShareMenu({
						isPrivateMessage: true,
						withShareTicket: true
					});
					return {
						title: this.liveShareInfo.liveName, //自定义标题
						path: '/pages/home/index?liveId=' + this.liveShareInfo.id + '&code=' + this.user.id + '&type=1' +
							`&tabCur=${this.tabCur}`,
						imageUrl: this.liveShareInfo.stopImage //自定义展示图片
					};
				}
			},
			async onLoad(options) {
				// scene=1688803573715230721$
				// options.liveId='1925447022222610434'
				JSON.stringify(options) == '{}' ? this.innerflag = true : this.innerflag = false
				this.user = uni.getStorageSync('user_info');
				// 设置ap参数
				if (options.token) {
					uni.setStorageSync("appToken", JSON.stringify(options));
				} 
				this.liveList = [];
				if (options.scene) {
					let scene = decodeURIComponent(options.scene);
					let arr = scene.split('$');
					this.liveId = arr[0];
					this.shareType = arr[1];
					app.initPage().then((response) => {
						this.bandUser();
					});
				} else if (options.liveId) {
					// if (new Date().getTime() - options.time > 1000 * 60 * 60 * 24) {
					// 	console.log("链接已失效");
					// 	return;
					// }
					this.liveId = options.liveId;
					this.shareType = options.type;
					this.tzUserId = options.code;
					// this.tabCur = options.tabCur ? options.tabCur : '1'
					await this.getLiveStatus()
					app.initPage().then((response) => {
						this.userInfoGet();
						this.getSwiper();
						if (this.tabCur == '1' || this.tabCur == '2') {
							let item = this.tab.find(ele => ele.value == this.tabCur)
							this.tabSelect(item)
							uni.navigateTo({
								url: '/pages/live/live?liveId=' + this.liveId
							});
							this.bandUser()
						} else {
							let isTab = true
							api.getliveList({
								...this.page,
								queryStatus: this.tabCur
							}).then((res) => {
								this.liveListLength = 0
								this.loadmore = true;
								if (isTab) {
									this.liveList = [];
								}
								this.loadmore = false;
								this.total = res.data.total;
								this.liveList.push(...res.data.records);
								if(this.liveList.length==this.total*2){
									this.liveList.splice(0,this.total)
								}
								this.liveListLength = this.liveList.length
								let item = this.liveList.find(ele => ele.id == this.liveId)
								let that=this
								uni.showModal({
								title: '提示',
								content: '直播已结束，请点击确定进入回放',
								success: function (res) {
									if (res.confirm) {
									 that.bandUser()
									} else if (res.cancel) {
										return
									}
								}
							});
							});
						}
					});
				} else {
					app.initPage().then((response) => {
						this.getLiveList();
						this.userInfoGet();
						this.getSwiper();
					});
				}
			},
			onReachBottom() {
				if (this.liveList.length < this.total) {
					this.page.current++;
					this.getLiveList();
				}
			},
			methods: {
				getLiveStatus(){
				 return new Promise((resolve, reject) => {
					 api.getLiveStatus({liveId:this.liveId}).then(res=>{
						 this.tabCur=res.data.status
						  resolve()
					 })	
				 })
				},
				userInfoGet() {
					let userInfo = uni.getStorageSync('user_info');
					if (userInfo.id) {
						api.userInfoGet().then((res) => {
							this.user = res.data;
						});
					} else {
						this.user = userInfo;
					}

					//分销设置
					// api.distributionConfig().then((res) => {
					// 	this.distributionConfig = res.data;
					// });
				},
				liveShare(item) {
					this.liveShareInfo = item;
				},
				bandUser() {
					let para = {
						liveId: this.liveId,
						userId: this.user.id
					};
					if (this.shareType == '1') {
						para.tzUserId = this.tzUserId;
					}
					api.liveBandUser(para).then((res) => {
						console.log(res, 'res');
						this.getLiveInfo();
						this.getLiveList();
					});
				},
				goLive(item) {
					if (this.tabCur == '3') {
						let playbackLIst = uni.getStorageSync('playbackLIst');
						if (playbackLIst.length) {
							if (playbackLIst.some((e) => e.id == item.id)) {
								uni.navigateTo({
									url: '/pages/live/live?liveId=' + item.id + '&isPlayBack=1'
								});
								return;
							}
						}
						uni.showModal({
							title: '密码',
							editable: true,
							placeholderText: '请输入密码',
							success: ({
								confirm,
								cancel,
								content
							}) => {
								if (confirm) {
									if (content == item.playbackPassword) {
										let playbackLIst = uni.getStorageSync('playbackLIst');
										playbackLIst = playbackLIst ? playbackLIst : [];
										console.log(playbackLIst);
										playbackLIst.push({
											id: item.id,
											playbackPassword: item.playbackPassword
										});
										uni.setStorageSync('playbackLIst', playbackLIst);
										uni.navigateTo({
											url: '/pages/live/live?liveId=' + item.id + '&isPlayBack=1'
										});
									} else {
										uni.showToast({
											title: '密码错误',
											icon: 'error',
											mask: true
										});
									}
								}
							}
						});
						return;
					}
					if (this.tabCur == '1') {
						if (this.user.tzFlag != 1) {
							api.subscriptionTemplate().then((res) => {
								let tmplIds = res.data.map((e) => e.pritmplId);
								let liveWxMsgList = res.data;
								// let liveWxMsgList = res.data.map((e) => {
								// 	return {
								// 		appId: e.appId,
								// 		enable: e.enable,
								// 		page: e.page,
								// 		pritmplId: e.pritmplId,
								// 		priTmplTitle: e.pritmplName,
								// 	};
								// });
								console.log(liveWxMsgList, 'liveWxMsgList');
								let liveId = item.id;
								uni.requestSubscribeMessage({
									tmplIds,
									success(res) {
										let para = {
											liveId: liveId,
											userId: uni.getStorageSync('user_info').id,
											liveWxMsgList: liveWxMsgList,
											// appId: 'wx64b438c07d5ced1d',
											appId: 'wx263c670291b3b46c'
										};
										api.livepritmpl(para).then((val) => {
											uni.showToast({
												title: '订阅成功',
												icon: 'success',
												mask: true
											});
											this.getLiveList();
										});
									}
								});
							});
							return;
						}
						if (item.isReward == 0) {
							uni.navigateTo({
								url: '/pages/live/Settings/Settings?liveId=' + item.id
							});
						} else {
							uni.navigateTo({
								url: '/pages/live/Settings/Settings?liveId=' + item.id + '&isEdit=1'
							});
						}

						// uni.showToast({
						// 	title: "未开始",
						// 	icon: "error",
						// 	mask: true,
						// });
						return;
					}
					// if (this.tabCur == "2") {
					// 	let para = {
					// 		liveId: item.id,
					// 		userId: this.user.id,
					// 	};
					// 	api.liveblacklistuser(para).then((res) => {
					// 		uni.navigateTo({
					// 			url: "/pages/live/live?liveId=" + item.id,
					// 		});
					// 	});
					// 	return;
					// }
					console.log(item.id)
					uni.navigateTo({
						url: '/pages/live/live?liveId=' + item.id
					});
				},
				tabSelect(item) {
					this.tabCur = item.value;
					this.page.current = 1;
					this.liveList = [];
					this.getLiveList(true);
				},
				getLiveInfo() {
					api.getliveList({
						...this.page,
						liveId: this.liveId
					}).then((res) => {

						if (res.data.records && res.data.records.length) {
							let index = res.data.records.findIndex((item) => item.id == this.liveId);
							let item = res.data.records[index];
							let status = item.statusDesc == '直播中' ? '2' : item.statusDesc == '未开始' ? '1' : '3';
							this.tabCur = status;
							if (status == '3') {
								this.tabSelect({
									value: status,
									title: item.statusDesc
								});
								this.goLive(item);
							} else {
								this.tabSelect({
									value: status,
									title: item.statusDesc
								});
							}
						}
					});
				},
				getLiveList(isTab = false) {
					this.loadmore = true;
					api.getliveList({
						...this.page,
						queryStatus: this.tabCur
					}).then((res) => {
						this.liveListLength = 0
						if (isTab) {
							this.liveList = [];
						}
						this.loadmore = false;
						this.total = res.data.total;
						this.liveList.push(...res.data.records);
						if(this.liveList.length==this.total*2){
							this.liveList.splice(0,this.total)
						}
						this.liveListLength = this.liveList.length
					});
				},
				getSwiper() {
					api.getSwiper().then((res) => {
						this.swiperList = res.data;
						if (this.swiperList.length) {
							this.swiperList = this.swiperList.filter((el) => el.status == 1);
						}
					});
				}
			}
		};
</script>
<style lang="scss" scoped>
	.user {
		display: flex;
		align-items: center;
		padding: 40rpx 30rpx;
		background-color: #fff;

		.avtar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			margin-right: 30rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 50%;
			}
		}
	}

	.live-list {
		padding: 10rpx 30rpx 30rpx;

		.live-item {
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 16rpx;

			.coverImage {
				width: 300rpx;
				height: 200rpx;
				margin-right: 30rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.content {
		height: 200rpx;
	}

	.jumpAd {
		position: absolute;
		top: 20rpx;
		right: 30rpx;
		color: #fff;
	}
</style>